<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\service\ApiService;
use think\facade\Db;
use think\facade\Validate;

class Task extends BaseController
{
    protected $apiService;
    
    public function __construct(ApiService $apiService)
    {
        $this->apiService = $apiService;
    }

    /**
     * 创建任务
     */
    public function create()
    {
        $data = $this->request->post();
        $userId = $this->request->user->uid;

        // 验证数据
        $validate = Validate::rule([
            'name' => 'require|max:100'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 创建任务
        $taskId = Db::name('tasks')->insertGetId([
            'user_id' => $userId,
            'name' => $data['name'],
            'status' => 0,
            'create_time' => time(),
            'update_time' => time()
        ]);

        return json([
            'code' => 200,
            'msg' => '创建成功',
            'data' => [
                'task_id' => $taskId
            ]
        ]);
    }

    /**
     * 更新POI信息
     */
    public function updatePoi()
    {
        $data = $this->request->post();
        $userId = $this->request->user->uid;

        // 验证数据
        $validate = Validate::rule([
            'task_id' => 'require|number',
            'poi_id' => 'require',
            'poi_name' => 'require',
            'poi_address' => 'require',
            'poi_latitude' => 'require',
            'poi_longitude' => 'require'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 检查任务是否存在且属于当前用户
        $task = Db::name('tasks')
            ->where('id', $data['task_id'])
            ->where('user_id', $userId)
            ->find();

        if (!$task) {
            return json(['code' => 404, 'msg' => '任务不存在']);
        }

        // 更新POI信息
        Db::name('tasks')->where('id', $data['task_id'])->update([
            'poi_id' => $data['poi_id'],
            'poi_name' => $data['poi_name'],
            'poi_address' => $data['poi_address'],
            'poi_latitude' => $data['poi_latitude'],
            'poi_longitude' => $data['poi_longitude'],
            'update_time' => time()
        ]);

        return json(['code' => 200, 'msg' => '更新成功']);
    }

    /**
     * 更新关键词和生成文案
     */
    public function updateScript()
    {
        $data = $this->request->post();
        $userId = $this->request->user->uid;

        // 验证数据
        $validate = Validate::rule([
            'task_id' => 'require|number',
            'keywords' => 'require'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 检查任务是否存在且属于当前用户
        $task = Db::name('tasks')
            ->where('id', $data['task_id'])
            ->where('user_id', $userId)
            ->find();

        if (!$task) {
            return json(['code' => 404, 'msg' => '任务不存在']);
        }

        try {
            // 调用豆包API生成文案
            $script = $this->generateScript($data['keywords'], $task['poi_name'], $task['poi_address']);

            // 更新任务
            Db::name('tasks')->where('id', $data['task_id'])->update([
                'keywords' => $data['keywords'],
                'script' => $script,
                'update_time' => time()
            ]);

            return json([
                'code' => 200,
                'msg' => '更新成功',
                'data' => [
                    'script' => $script
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '生成文案失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新视频URL
     */
    public function updateVideos()
    {
        $data = $this->request->post();
        $userId = $this->request->user->uid;

        // 验证数据
        $validate = Validate::rule([
            'task_id' => 'require|number',
            'video_urls' => 'require|array'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 检查任务是否存在且属于当前用户
        $task = Db::name('tasks')
            ->where('id', $data['task_id'])
            ->where('user_id', $userId)
            ->find();

        if (!$task) {
            return json(['code' => 404, 'msg' => '任务不存在']);
        }

        // 更新视频URL
        Db::name('tasks')->where('id', $data['task_id'])->update([
            'video_urls' => json_encode($data['video_urls']),
            'status' => 1, // 标记任务完成
            'update_time' => time()
        ]);

        return json(['code' => 200, 'msg' => '更新成功']);
    }

    /**
     * 获取任务列表
     */
    public function list()
    {
        $userId = $this->request->user->uid;
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);

        $tasks = Db::name('tasks')
            ->where('user_id', $userId)
            ->order('create_time', 'desc')
            ->page($page, $limit)
            ->select();

        $total = Db::name('tasks')
            ->where('user_id', $userId)
            ->count();

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'list' => $tasks,
                'total' => $total,
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }

    /**
     * 获取任务详情
     */
    public function detail()
    {
        $taskId = $this->request->param('task_id');
        $userId = $this->request->user->uid;

        $task = Db::name('tasks')
            ->where('id', $taskId)
            ->where('user_id', $userId)
            ->find();

        if (!$task) {
            return json(['code' => 404, 'msg' => '任务不存在']);
        }

        // 处理视频URL列表
        if ($task['video_urls']) {
            $task['video_urls'] = json_decode($task['video_urls'], true);
        }

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $task
        ]);
    }

    /**
     * 搜索POI
     */
    public function searchPoi()
    {
        $keyword = $this->request->param('keyword');
        $latitude = $this->request->param('latitude');
        $longitude = $this->request->param('longitude');

        if (empty($keyword)) {
            return json(['code' => 400, 'msg' => '请输入搜索关键词']);
        }

        try {
            $poiList = $this->apiService->searchPoi($keyword, $latitude, $longitude);
            return json([
                'code' => 200,
                'msg' => '搜索成功',
                'data' => $poiList
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '搜索失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取POI详情
     */
    public function getPoiDetail()
    {
        $poiId = $this->request->param('poi_id');

        if (empty($poiId)) {
            return json(['code' => 400, 'msg' => 'POI ID不能为空']);
        }

        try {
            $poiDetail = $this->apiService->getPoiDetail($poiId);
            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => $poiDetail
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败：' . $e->getMessage()]);
        }
    }

    /**
     * 调用豆包API生成文案
     */
    protected function generateScript($keywords, $poiName, $poiAddress)
    {
        return $this->apiService->generateScript($keywords, $poiName, $poiAddress);
    }
} 